//
//  KADayViewController.m
//  KeepAccounts
//
//  Created by honeyrr on 2017/10/24.
//  Copyright © 2017年 honeyrr. All rights reserved.
//

#import "KADayViewController.h"
#import "KADayTableViewCell.h"
#import "KADayTableHeaderView.h"
#import "CCColorCube.h"
#import "KAPieChartView.h"

@interface KADayViewController ()<UITableViewDelegate, UITableViewDataSource, KAPieChartViewDelegate>

@property(nonatomic, strong) KAPieChartView *pieChartView;
@property(nonatomic, assign) CGRect pieChartFrame;
@property(nonatomic, strong) UILabel *datelabel;

@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, assign) int year;
@property(nonatomic, assign) int month;
@property(nonatomic, assign) int day;
@property(nonatomic, assign) BOOL isOutlay;

@property(nonatomic, strong) NSArray *dayTableArr;

@property(nonatomic, assign) int incomeSum;
@property(nonatomic, assign) int outlaySum;

@property(nonatomic, strong) NSArray *incomeStatistics;
@property(nonatomic, strong) NSArray *outlayStatistics;

@property(nonatomic, strong) NSArray *noData;
@end

static NSString *const ID = @"cellID";

@implementation KADayViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.dayTableArr = [[KAQueryDataBaseModel instance] queryCurrentDayData:self.datelabel.text];
    self.isOutlay = false;
    [self reloadPieChartsData];
    [self.tableView reloadData];
}

-(NSArray *)incomeStatistics
{
    if (!_incomeStatistics) {
        _incomeStatistics = [NSArray array];
    }
    return _incomeStatistics;
}
-(NSArray *)outlayStatistics
{
    if (!_outlayStatistics) {
        _outlayStatistics = [NSArray array];
    }
    return _outlayStatistics;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpUI];
    
}

-(void) setUpUI
{
    self.noData = @[@[@"暂无数据"],@[@"100%"],@[[UIColor clearColor]]];
    NSDateFormatter *date = [[NSDateFormatter alloc] init];
    date.dateFormat = @"yyyy-MM-dd";
    NSString *today = [date stringFromDate:[NSDate date]];
    NSArray *dateArr = [today componentsSeparatedByString:@"-"];
    self.year = [dateArr[0] intValue];
    self.month = [dateArr[1] intValue];
    self.day = [dateArr[2] intValue];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *dateView = [UIView new];
    dateView.frame = CGRectMake(0, 0, KAScreenW, 44);
    dateView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:dateView];
    [self setHeaderDateView:dateView];
    self.dayTableArr = [[KAQueryDataBaseModel instance] queryCurrentDayData:self.datelabel.text];
    
    self.pieChartView = [[KAPieChartView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(dateView.frame), KAScreenW, KAScreenW * 0.66)];
    self.pieChartView.delegate = self;
    [self.view addSubview:self.pieChartView];
    
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
}

-(void)onCenterClick:(KAPieChartView *)pieChartView
{
    self.isOutlay = !self.isOutlay;
    [self.tableView reloadData];
}

-(void)setHeaderDateView:(UIView *)view
{
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(50, 7, 30, 30)];
    [leftBtn setImage:[UIImage imageNamed:@"icon_prev"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftClick) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:leftBtn];
    
    CGFloat Y = 7;
    CGFloat W = 100;
    CGFloat H = 30;
    CGFloat X = view.frame.size.width/2 - W/2;
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(X, Y, W, H)];
    label.text = [NSString stringWithFormat:@"%d-%02d-%02d",self.year,self.month,self.day];
    label.textAlignment = NSTextAlignmentCenter;
    [view addSubview:label];
    self.datelabel = label;
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(view.frame.size.width - 50 - 30, 7, 30, 30)];
    [rightBtn setImage:[UIImage imageNamed:@"icon_next"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:rightBtn];
}

-(NSArray *)dayTableArr
{
    if (!_dayTableArr) {
        _dayTableArr = [NSArray array];
    }
    return _dayTableArr;
}

-(void)leftClick
{
    self.isOutlay = false;
    self.day --;
    if (self.day < 1) {
        self.month --;
        self.day =  [self howManyDaysInThisYear:self.year withMonth:self.month];
        if (self.month < 1) {
            self.year --;
            self.month = 12;
            self.day =  [self howManyDaysInThisYear:self.year withMonth:self.month];
        }
    }
    self.datelabel.text = [NSString stringWithFormat:@"%d-%02d-%02d",self.year,self.month,self.day];
    self.dayTableArr = [[KAQueryDataBaseModel instance] queryCurrentDayData:self.datelabel.text];
    [self.tableView reloadData];
    
    [self reloadPieChartsData];
}

-(void) rightClick
{
    self.isOutlay = false;
    self.day ++;
    
    if (self.day > [self howManyDaysInThisYear:self.year withMonth:self.month]) {
        self.month ++;
        self.day =  1;
        if (self.month > 12) {
            self.year ++;
            self.month = 1;
        }
    }
    self.datelabel.text = [NSString stringWithFormat:@"%d-%02d-%02d",self.year,self.month,self.day];
    self.dayTableArr = [[KAQueryDataBaseModel instance] queryCurrentDayData:self.datelabel.text];
    [self.tableView reloadData];
    
    [self reloadPieChartsData];
    
}
-(void)reloadPieChartsData
{
    [self loadIncomeAndOutlaySum];
    [self loadPieDate];
    self.pieChartView.isOutlay = false;
    self.pieChartView.pieMarr = @[self.incomeStatistics,self.outlayStatistics];
    self.pieChartView.allIncomeMoney = self.incomeSum;
    self.pieChartView.allOutlayMoney = self.outlaySum;
}


- (int)howManyDaysInThisYear:(int)year withMonth:(int)month{
    if((month == 1) || (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12)) return 31;
    if((month == 4) || (month == 6) || (month == 9) || (month == 11)) return 30;
    if((year % 4 == 1) || (year % 4 == 2) || (year % 4 == 3)) {
        return 28;
    }
    if(year % 400 == 0)
        return 29;
    if(year % 100 == 0)
        return 28;
    return 29;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tv = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.pieChartView.frame) + 10, KAScreenW, KAScreenH - CGRectGetMaxY(self.pieChartView.frame) - 10  - 49 - 64) style:UITableViewStylePlain];
        tv.delegate = self;
        tv.dataSource = self;
        tv.bounces = NO;
        tv.separatorStyle = UITableViewCellSeparatorStyleNone;
        tv.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        [tv registerNib:[UINib nibWithNibName:NSStringFromClass(KADayTableViewCell.class) bundle:nil] forCellReuseIdentifier:ID];
        tv.tableFooterView = [UIView new];
        _tableView = tv;
    }
    return _tableView;
}

-(void) loadIncomeAndOutlaySum
{
    self.incomeSum = 0;
    self.outlaySum = 0;
    for (int i = 0; i < self.dayTableArr.count; i ++) {
        if (i == 0) {
            for (int j = 0; j < [self.dayTableArr[i] count]; j ++) {
                self.incomeSum += [[[self.dayTableArr[i] objectAtIndex:j] money] intValue];
            }
        } else {
            for (int j = 0; j < [self.dayTableArr[i] count]; j ++) {
                self.outlaySum += [[[self.dayTableArr[i] objectAtIndex:j] money] intValue];
            }
        }
    }
}

#pragma mark - 加载饼图数据
-(void) loadPieDate{
    NSMutableArray *marr1 = [self mergeSameDate:self.dayTableArr[0]];
    NSMutableArray *marr2 = [self mergeSameDate:self.dayTableArr[1]];
    NSLog(@"收入%@----支出%@",marr1,marr2);
    
    NSMutableArray *colorIncomeMarr = [NSMutableArray arrayWithArray:[self getIncomeOrOutlayColor:marr1] ];
    NSMutableArray *colorOutlayMarr = [NSMutableArray arrayWithArray:[self getIncomeOrOutlayColor:marr2]];
    
    NSMutableArray *percentIncomeMarr = [NSMutableArray array];
    NSMutableArray *percentOutlayMarr = [NSMutableArray array];
    for (NSDictionary *dict in marr1) {
        float money = [dict[@"money"] intValue];
        double temp = money / self.incomeSum;
        NSString *percent = [NSString stringWithFormat:@"%.01f%%", temp * 100];
        [percentIncomeMarr addObject:percent];
    }
    for (NSDictionary *dict in marr2) {
        float money = [dict[@"money"] intValue];
        double temp = money / self.outlaySum;
        
        NSString *percent = [NSString stringWithFormat:@"%.01f%%", temp * 100];
        [percentOutlayMarr addObject:percent];
    }
    
    self.incomeStatistics = @[marr1,percentIncomeMarr,colorIncomeMarr];
    self.outlayStatistics = @[marr2,percentOutlayMarr,colorOutlayMarr];
}
#pragma mark - 合并元素
-(NSMutableArray *) getIncomeOrOutlayColor:(NSMutableArray *)marr
{
    NSMutableArray *colorMarr = [NSMutableArray array];
    for (NSDictionary *dict in marr) {
        [colorMarr addObject:[self extractColorFromImage:[UIImage imageNamed:dict[@"imageName"]]]];
    }
    return colorMarr;
}
#pragma mark - 从图片提取颜色
- (UIColor *)extractColorFromImage:(UIImage *)image
{
    CCColorCube *cube = [[CCColorCube alloc] init];
    NSArray *colors = [cube extractColorsFromImage:image flags:CCAvoidBlack count:1];
    // 由于我们的图标都是单色的，因此直接取第一个元素即为我们所需要的颜色
    return colors.firstObject;
}
#pragma mark - 合并账单
-(NSMutableArray *)mergeSameDate:(NSMutableArray *)arr
{
    NSMutableArray *dateArray = [NSMutableArray array];
    for (int i = 0; i < arr.count; i ++) {
        NSString *string = [arr[i] name];
        NSMutableArray *tempArray = [NSMutableArray new];
        for (int j = 0; j < arr.count; j ++) {
            NSString *jstring = [arr[j] name];
            if([string isEqualToString:jstring]){
                [tempArray addObject:arr[j]];
            }
        }
        //如果tempArray.count > 1 将他添加至数组
        if ([tempArray count] > 1) {
            [dateArray addObject:tempArray];
        }
        //移除出现相同次数的元素
        for (int i = 0; i < [tempArray count] - 1; i++) {
            for (int j=0; j<arr.count; j++) {
                if ([[tempArray[i] name] isEqualToString:[arr[j] name]]) {
                    [arr removeObject:arr[j]];
                }
            }
        }
    }
    for (KADataBaseModel *model in arr) {
        BOOL isSame = false;
        for (int i=0; i<dateArray.count; i++) {
            NSString *name = [dateArray[i][0] name];
            if ([model.name isEqualToString:name]) {
                isSame = true;
            }
        }
        if (!isSame) {
            [dateArray addObject:@[model]];
        }
    }
    
    NSMutableArray *resultArr = [NSMutableArray array];
    for (NSArray *arr in dateArray) {
        int sum = 0;
        for (int i=0; i<arr.count; i++) {
            sum += [[arr[i] money] intValue];
        }
        NSDictionary *dict = @{@"name":[arr[0] name], @"money":[NSString stringWithFormat:@"%d",sum], @"imageName":[arr[0] imageName]};
        [resultArr addObject:dict];
    }
    return resultArr;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (!_isOutlay) {
        return [[self.dayTableArr objectAtIndex:0] count];
    } else {
        return [self.dayTableArr[1] count];
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    KADayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[KADayTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    if (!_isOutlay) {
        cell.dayModel = self.dayTableArr[0][indexPath.row];
    } else {
        cell.dayModel = self.dayTableArr[1][indexPath.row];
    }
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    KADayTableHeaderView *headerView = [[KADayTableHeaderView alloc]initWithFrame:CGRectMake(0, 0, KAScreenW, 30)];
    return headerView;
}

@end
